<template>
    <a-modal class="goods-select-modal" :width="820" :visible="true" cancel-text="取消[Esc]" ok-text="确认[Enter]" @ok="handleOk" @cancel="handleCancel">
        <ConfigProvider>
    <template #renderEmpty>
      <a-empty description="没有找到商品，请确认商品是否上架"> </a-empty>
    </template>
        <a-table bordered ref="tableRef" :rowClassName="(record,index)=>{
            return state.current===index?'active-row':'';
        }" :columns="columns" :dataSource="state.goodsList" :pagination="false" :scroll="{y:400}">
          <template #bodyCell="{record,column}">
                    <template v-if="column.dataIndex==='goodsCode'">
                        {{ record.goodsCode || record.id }}
                    </template>
                    <template v-if="column.dataIndex==='goodsName'">
                        {{ record.goodsName || record.title}}
                    </template>
                    <template v-if="column.dataIndex==='type'">
                        {{ record.goodsCode?"商品":"套餐" }}
                    </template>
                </template>    
    </a-table>
    </ConfigProvider>
    </a-modal>
</template>
<script lang="ts" setup>

import { ConfigProvider } from "ant-design-vue";
import { reactive,onMounted,onBeforeUnmount,nextTick,ref } from "vue";
import { GoodsService,PackageService} from "@/service/index";
import { message } from "ant-design-vue";
import { GoodsStatusEnum, GoodsTypes } from "@/type";

const props = defineProps<{
    inputValue:string|number,
   
}>()

const state = reactive<{
    goodsList:any[];
    current:number;
}>({
    goodsList:[],
    current:0
})

const tableRef = ref()

const emit = defineEmits<{
    (e:"ok",value:any):void,
    (e:"cancel"):void
}>()

onMounted(async()=>{
    await getGoodsElements();
    await getPackageElements();
    window.addEventListener("keydown",handleKeydown)
})

onBeforeUnmount(()=>{
    window.removeEventListener("keydown",handleKeydown)
})

const handleKeydown = (e:any)=>{
    e.preventDefault();
    const code = e.code;
    if(code === "ArrowDown"){
        state.current++;
        if(state.current>state.goodsList.length-1)state.current=0;
    }else if(code === "ArrowUp"){
        state.current--;
        if(state.current<0)state.current=state.goodsList.length-1;
    }else if(code === "Enter" || code==="NumpadEnter"){
        handleOk()
        return
    }else if(code === "Esc"){
        handleCancel()
        return
    }

    nextTick(()=>{
       let pos = (document.querySelector(".active-row") as HTMLDivElement).getBoundingClientRect();
       const tableBody = tableRef.value.$el.querySelector(".ant-table-body");
       let tablePos = tableBody.getBoundingClientRect();

     
       let scrollTop = pos.top+pos.height+tableBody.scrollTop - tablePos.top - tablePos.height;
       tableBody.scrollTop = scrollTop>0?scrollTop:0
    })
}

const columns = [
    {title:"商品/套餐编码",dataIndex:"goodsCode",width:160},
    {title:"商品/套餐名称",dataIndex:"goodsName",ellipse:true,},
    {title:"类型",dataIndex:"type"}
]

const getGoodsElements = async()=>{
    const params:{
        goodsCode?: number | undefined;
        goodsName?: string | undefined;
        pageNum: number,
        pageSize: number,
        status:GoodsStatusEnum
    } = {
        pageNum: 1,
        pageSize:999,
        status: GoodsStatusEnum.ONSALE
    }
    if(/^\d+$/.test(props.inputValue+'')){
        params.goodsCode = Number(props.inputValue)
    }else{
        params.goodsName = props.inputValue as string;
    }

    let res = await GoodsService.pageGoods(params);
    if(res.code===0){
        state.goodsList = res.data?.list.filter((goods:GoodsTypes.IGoodsItem)=>{
            return goods.status==GoodsStatusEnum.ONSALE
        }) || [];
    }
}

const getPackageElements = async()=>{
    const params:{
        title?:string,
        packageId?:string,
        pageNum: number,
        pageSize: number,
        status:GoodsStatusEnum
  
    } = {
        pageNum: 1,
        pageSize:999,
        status: GoodsStatusEnum.ONSALE
    }
    if(/^\d+$/.test(props.inputValue+'')){
        params.packageId = props.inputValue as string;
    }else{
        params.title = props.inputValue as string;
    }

    let res = await PackageService.pagePackage(params);
    if(res.code===0){
        state.goodsList = [...state.goodsList,...(res.data?.list.map((item:any)=>{
            item.packageId = item.id;
            item.packageName = item.title;
            return item;
        }) || [])];
    }
}

const handleOk = ()=>{
    let val = state.goodsList[state.current];
    console.log(val)
    if(val){
        emit("ok",val);
    }else{
        return message.error("没有选择商品")
    }
    
}

const handleCancel = ()=>{
    emit("cancel");
}

</script>

<style lang="less" >

.goods-select-modal .ant-table-row.active-row{
    .ant-table-cell{
        border-top: 2px solid #7546c9;
        border-bottom: 2px solid #7546c9;
        background-color:lighten(#7546c9,40)
    }    
}

</style>